<?php
/**
 * Created by PhpStorm.
 * User: chang
 * Date: 2019/4/1
 * Time: 11:54
 */

namespace App\Http\Model;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class UserProp extends Model
{
    protected $redisKeyUserPropUseList = 'USER:PROP:USE:LIST:'; //道具使用key PROP:USE:LIST:eventType:userId
    protected $redisKeyUserPropUseInvalid = 'USER:PROP:USE:INVALID:'; //道具使用失效方案处理

    /**
     * 道具使用时间设置
     *
     * @param int $userId 用户ID
     * @param int $propEventType 道具功能Type
     * @param int $time 使用时间
     * @param int $dataId 选择数据Id
     * @return boolean
     * */
    public function setPropUseTime($userId, $propEventType, $time, $dataId = null)
    {
        $key = $this->redisKeyUserPropUseList . $propEventType . ":" . $userId;

        if ($dataId != null) {
            $key = $this->redisKeyUserPropUseList . $propEventType . ":" . $userId . ":" . $dataId;
        }

        $redisTime = Redis::GET($key);
        if ($redisTime) {
            Redis::SET($key, $redisTime + $time);
        } else {
            Redis::SET($key, time() + $time);
        }

        $exTime = $redisTime ? $redisTime + $time : time() + $time;

        Redis::EXPIREAT($key, $exTime);
        return true;
    }

    /**
     * 道具使用时间获取
     *
     * @param int $userId 用户ID
     * @param int $propEventType 15=隐身衣 16=足迹清除卡 17=甜蜜蛋糕 18=亲密度直升卡 19=防跟随
     * @param int $dataId 数据ID
     * @return string
     * */
    public function getPropUseTime($userId, $propEventType, $dataId = null)
    {
        $key = $this->redisKeyUserPropUseList . $propEventType . ":" . $userId;
        if ($dataId != null) {
            $key = $this->redisKeyUserPropUseList . $propEventType . ":" . $userId . ":" . $dataId;
        }

        //查询隐身衣临时失效
        if ($propEventType == 15) {
            $propInvalidKey = $this->redisKeyUserPropUseInvalid . $propEventType . ":" . $userId;
            $propInvalid =  Redis::GET($propInvalidKey);
            if ($propInvalid) return false;
        }

        return Redis::get($key);
    }

    /**
     * 道具临时失效设置
     *
     * @param int $userId 用户ID
     * @param int $propEventType 道具功能Type
     * @return boolean
     * */
    public function setPropInvalid($userId, $propEventType)
    {
        $key = $this->redisKeyUserPropUseInvalid . $propEventType . ":" . $userId;
        return Redis::SET($key, time(), 'EX', 24 * 60 * 60);
    }

    /**
     * 道具临时失效设置清除
     *
     * @param int $userId 用户ID
     * @param int $propEventType 道具功能Type
     * @return boolean
     * */
    public function resetPropInvalid($userId, $propEventType)
    {
        $key = $this->redisKeyUserPropUseInvalid . $propEventType . ":" . $userId;
        return Redis::DEL($key);
    }
}